package com.crm.interceptor;

import com.crm.pojo.common.UserContext;
import com.crm.pojo.domain.LoginUser;
import com.crm.pojo.domain.User;
import com.crm.pojo.vo.RoleVo;
import com.crm.service.RoleService;
import com.crm.service.UserService;
import com.crm.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class UserContextInterceptor implements HandlerInterceptor {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取 token
        String token = request.getHeader("Authorization");
        
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer " 前缀
            
            // 验证 token 有效性
            if (jwtUtil.validateToken(token)) {
                // 从 token 中获取用户名
                String username = jwtUtil.getUsernameFromToken(token);
                
                if (username != null) {
                    // 根据用户名获取完整用户信息
                    User user = userService.getUserByUserName(username);
                    if (user != null) {
                        // 将用户信息设置到 UserContext中
                        LoginUser loginUser = new LoginUser();
                        BeanUtils.copyProperties(user, loginUser);
                        List<RoleVo> roles = roleService.roles(user.getUserId());
                        loginUser.setRoles( roles);
                        UserContext.setUser(loginUser);
                    }
                }
            }
        }
        
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成后清理 ThreadLocal
        UserContext.clear();
    }
}
